'use client';

import { useState, useEffect, useRef } from 'react';

export default function WebSocketPage() {
  const [userId, setUserId] = useState('user_' + Math.floor(Math.random() * 1000));
  const [message, setMessage] = useState('');
  const [chatHistory, setChatHistory] = useState<string[]>([]);
  const [isConnected, setIsConnected] = useState(false);
  const [onlineUsers, setOnlineUsers] = useState(0);
  
  // WebSocket实例的引用
  const webSocketRef = useRef<WebSocket | null>(null);

  // 连接WebSocket
  const connectWebSocket = () => {
    // 关闭现有连接
    if (webSocketRef.current) {
      webSocketRef.current.close();
    }
    
    // 创建新连接
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    // const wsUrl = `${wsProtocol}//${window.location.host}/websocket/${userId}`;
    const wsUrl = `${wsProtocol}//localhost:8099/websocket/${userId}`;
    webSocketRef.current = new WebSocket(wsUrl);
    
    // 连接成功
    webSocketRef.current.onopen = () => {
      console.log('WebSocket连接成功');
      setIsConnected(true);
      addMessageToHistory('已连接到服务器');
    };
    
    // 接收消息
    webSocketRef.current.onmessage = (event) => {
      console.log('收到消息:', event.data);
      addMessageToHistory(event.data);
      
      // 简单解析在线人数（实际应用中可能需要更复杂的逻辑）
      const onlineMatch = event.data.match(/当前在线人数为(\d+)/);
      if (onlineMatch && onlineMatch[1]) {
        setOnlineUsers(parseInt(onlineMatch[1]));
      }
    };
    
    // 连接关闭
    webSocketRef.current.onclose = () => {
      console.log('WebSocket连接关闭');
      setIsConnected(false);
      addMessageToHistory('与服务器断开连接');
    };
    
    // 连接错误
    webSocketRef.current.onerror = (error) => {
      console.error('WebSocket错误:', error);
      addMessageToHistory('连接错误，请重试');
    };
  };

  // 断开连接
  const disconnectWebSocket = () => {
    if (webSocketRef.current) {
      webSocketRef.current.close();
      webSocketRef.current = null;
      setIsConnected(false);
    }
  };

  // 发送消息
  const sendMessage = () => {
    if (!webSocketRef.current || webSocketRef.current.readyState !== WebSocket.OPEN || !message.trim()) {
      return;
    }
    
    webSocketRef.current.send(message.trim());
    setMessage('');
  };

  // 添加消息到历史记录
  const addMessageToHistory = (msg: string) => {
    setChatHistory(prev => [...prev, msg].slice(-50)); // 只保留最近50条消息
  };

  // 组件挂载时连接WebSocket
  useEffect(() => {
    connectWebSocket();
    
    // 组件卸载时关闭连接
    return () => {
      disconnectWebSocket();
    };
  }, [userId]);




  return (
    <div className="max-w-2xl mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">WebSocket 聊天</h1>
      
      <div className="mb-4">
        <label className="block mb-2">用户ID:</label>
        <input
          type="text"
          value={userId}
          onChange={(e) => setUserId(e.target.value)}
          className="border p-2 w-full"
        />
        <button 
          onClick={connectWebSocket}
          className="mt-2 bg-blue-500 text-white p-2 rounded mr-2"
        >
          连接
        </button>
        <button 
          onClick={disconnectWebSocket}
          className="mt-2 bg-red-500 text-white p-2 rounded"
          disabled={!isConnected}
        >
          断开
        </button>
        <div className="mt-2 text-sm text-gray-600">
          连接状态: {isConnected ? '已连接' : '未连接'} | 在线人数: {onlineUsers}
        </div>
      </div>
      
      <div className="border h-64 overflow-y-auto p-2 mb-4 bg-gray-50">
        {chatHistory.map((msg, index) => (
          <div key={index} className="mb-1">{msg}</div>
        ))}
      </div>
      
      <div className="flex">
        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="输入消息..."
          className="border p-2 flex-1"
          disabled={!isConnected}
        />
        <button 
          onClick={sendMessage}
          className="bg-green-500 text-white p-2 px-4 ml-2"
          disabled={!isConnected || !message.trim()}
        >
          发送
        </button>
      </div>
    </div>
  );
}
    